package com.imist.jdbc.servlet;

import com.imist.jdbc.bean.Message;
import com.imist.jdbc.service.MessageService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class MessageListServlet extends HttpServlet {
    private MessageService messageService ;
    @Override
    public void init() throws ServletException {
        super.init();
        messageService = new MessageService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageStr = req.getParameter("page");//当前页码
        int  page = 1;//默认页码是1
        if (null != pageStr && !"".equals(pageStr)){
            try {
                page = Integer.parseInt(pageStr);
            }catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        List<Message> messages = messageService.getMessages(page,5);//分页查询全部留言
        int count = messageService.countMessages();
        int last = count%5 == 0 ? count/5 : count/5+1;
        req.setAttribute("last",last);
        req.setAttribute("messages",messages);
        req.setAttribute("page",page);
        req.getRequestDispatcher("/WEB-INF/views/biz/message_list.jsp").forward(req,resp);
    }

    @Override
    public void destroy() {
        super.destroy();
        messageService = null;
    }
}
